//
//  UINavigationController+Transparent.m
//  meets-ios
//
//  Created by Mark on 15/12/3.
//  Copyright © 2015年 meets. All rights reserved.
//

#import "UINavigationController+Transparent.h"
#import <objc/runtime.h>

static const void *TransparentNameKey = &TransparentNameKey;

@implementation UINavigationController (Transparent)

- (UIView *)transparentView {
    return objc_getAssociatedObject(self, TransparentNameKey);
}

- (void)setTransparentView:(UIView *)transparentView {
    objc_setAssociatedObject(self, TransparentNameKey, transparentView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

/**
 *  如果用setBackgroundColor方法，statusbar的颜色无法改变
 *  如果用setBarTintColor方法，因为调用了setBackgroundImage:forBarMetrics，所以会无效，全黑
 *  最终采用加一个subview
 *
 *  @param alpha alpha value
 */
- (void)setNavigationBarAlpha:(CGFloat)alpha withColor:(UIColor *)color {
    if (!self.transparentView) {
        self.transparentView = [UIView new];
        self.transparentView.size = CGSizeMake(self.navigationBar.width, self.navigationBar.height + STATUSBAR_HEIGHT);
        [self.view insertSubview:self.transparentView belowSubview:self.navigationBar];
        
        [self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
        [self.navigationBar setShadowImage:[UIImage new]];
    }
    
    [self.transparentView setBackgroundColor:color];
    [self.transparentView setAlpha:alpha];
    if (alpha < 0.6f) {
        [self.navigationBar setBarStyle:UIBarStyleBlack];
    } else {
        [self.navigationBar setBarStyle:UIBarStyleDefault];
    }
}

- (void)setNavigationBarOriginal {
    if (self.transparentView) {
        if ([self.transparentView superview]) {
            [self.transparentView removeFromSuperview];
        }
        self.transparentView = nil;
    }
    
    [self.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationBar setShadowImage:nil];
    [self.navigationBar setBarStyle:UIBarStyleDefault];
    [self.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: MeetOrange, NSFontAttributeName : TitleFont}];
}

@end
